﻿#include "serverreadsession.h"
#include "utils.h"

//#include <netinet/in.h>
#include <winsock.h>
#include <QFile>

namespace TFTP {

QMap<QString, Session::FileMappingItem> ServerReadSession::mapped;


ServerReadSession::ServerReadSession(TransferInfo &T, const QByteArray &dgram) :
	TFTP::ReadSession(T)
{
    if ( ntohs( wordOfArray(dgram)[0] ) != RRQ ){
        qFatal("使用非RRQ数据包创建的WriteSession");
    }

	m_currentFilename = QString(dgram.data() + 2);
    QString mode = QString( dgram.data() + 2 + m_currentFilename.length() + 1 );
    mode = mode.toLower();
	
    if ( mode == "netascii" )
    {
        currentMode = NetAscii;
    }else if ( mode == "octet" )
    {
        currentMode = Octet;
    }else if ( mode == "mail" ) { // Not supported
        ti.sendError(  IllegalOp, "不支持邮件传输");
		return;
	} else {
        ti.sendError(  IllegalOp, "非法传输模式");
		return;
	}
	
	if ( mapped.contains(m_currentFilename) )
	{
		m_currentFile = mapped[m_currentFilename].dev;

        if ( mapped[m_currentFilename].oneshot ){
            QMap<QString, FileMappingItem>::iterator it =  mapped.find(m_currentFilename);
            if(mapped.end() != it){
                mapped.erase(it);
            }
        }
	} else {
		QString filename = m_currentFilename;
		filename.replace('\\', '_');
		filename.replace('/', '_');
		m_currentFile = new QFile(filename);
        m_currentFile->open(QFile::ReadOnly);
		
	}
	
	loadFile();
	
	currentBlock = 0;
	
	sendData();
}


ServerReadSession::~ServerReadSession()
{
}


void ServerReadSession::remapFilename(const QString &oldname, QIODevice *dev, bool oneshot)
{
	mapped[oldname].dev = dev;
	mapped[oldname].oneshot = oneshot;
}


void ServerReadSession::unmapFilename(const QString &oldname)
{
    QMap<QString, FileMappingItem>::iterator it =  mapped.find(oldname);
    if(mapped.end() != it){
        mapped.erase(it);
    }
}

};
